// 根
const baseUrl = 'https://api.qyqbwbwk.com/'
// 排序
function sortObj (obj) {
  const newObj = {}
  if (obj) {
    Object.keys(obj).sort().map(key => {
      newObj[key] = obj[key]
    })
  }
  return JSON.stringify(newObj).replace(/\//g, '')
}
// 设置request
function AjaxRequest(opt){
  // 设置 sign
  try {
    // 文件上传处理
    opt.data.append('token', $.cookie('token'))
    const newObj = {}
    opt.data.forEach((value, key) => {
      if (key !== 'file_excel' && key !== 'file' && key !== 'file[]') {
        newObj[key] = value
      }
    })
    const sign = md5( sortObj(newObj) + '854351') // 生成sign
    opt.data.append('sign', sign)
  } catch (err) {
    opt.data = {
      token: $.cookie('token')||'',
      ...opt.data
    }
    const sign = md5(sortObj(opt.data)+ '854351') // 生成sign
    opt.data = {
      sign,
      ...opt.data
    }
  }
  var defaultSettings = {
    data:opt.data,
    type: 'post',
    dataType: 'JSON',
    success:function (res) {
      // if the custom code is not 20000, it is judged as an error.
      if (res.code !== 200) {
        layer.msg(res.message || 'Error 寻求后台帮助',{icon:2,time:1500});
        // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
        if (res.code === 100) {
          // to re-login
          //询问框
          layer.confirm(res.message, {
            title:'友情提示',
            btn: ['确定','取消'] //按钮
          }, function(){
            // 这里是登录过期
            if (top.location.href != location.href) {
              top.location.href ="login.html";
            }
          });
        }
      } else {
        opt.succFun && opt.succFun(res)
      }
    },
    error: function(xhr){
      if(xhr.status == 401){
        layer.msg('您未登录',{icon:2})
      }else if(xhr.status == 403){
        layer.msg('您没有权限',{icon:2})
      }else if(xhr.status == 500){
        layer.msg('服务器发生错误，请稍后刷新页面',{icon:2})
      }else{
        layer.msg('未知错误',{icon:2})
      }
    }
  }
  for(var key in opt){
    defaultSettings[key] = opt[key]
    if(key == 'url')
      defaultSettings[key] = baseUrl +'/index'+ opt[key]
  }
  if(arguments[1]){ //如果是图片上传,需要传递第二个参数，必须内容
    defaultSettings.traditional = true
    defaultSettings.processData = false
    defaultSettings.contentType = false
  }
  return $.ajax(defaultSettings)
}

//制动给form表单赋值
(function($){
  $.fn.extend({
    initForm:function(options){
      //默认参数
      var defaults = {
        jsonValue:options,
        isDebug:false   //是否需要调试，这个用于开发阶段，发布阶段请将设置为false，默认为false,true将会把name value打印出来
      }
      //设置参数
      var setting = defaults;
      var form = this;
      jsonValue = setting.jsonValue;
      //如果传入的json字符串，将转为json对象
      if($.type(setting.jsonValue) === "string"){
        jsonValue = $.parseJSON(jsonValue);
      }
      //如果传入的json对象为空，则不做任何操作
      if(!$.isEmptyObject(jsonValue)){
        var debugInfo = "";
        $.each(jsonValue,function(key,value){
          //是否开启调试，开启将会把name value打印出来
          if(setting.isDebug){
            alert("name:"+key+"; value:"+value);
            debugInfo += "name:"+key+"; value:"+value+" || ";
          }
          var formField = form.find("[name='"+key+"']");
          if($.type(formField[0]) === "undefined"){
            if(setting.isDebug){
              alert("can not find name:["+key+"] in form!!!");    //没找到指定name的表单
            }
          } else {
            var fieldTagName = formField[0].tagName.toLowerCase();
            if(fieldTagName == "input"){
              if(formField.attr("type") == "radio"){
                $("input:radio[name='"+key+"'][value='"+value+"']").attr("checked","checked");
              } else {
                formField.val(value);
              }
            } else if(fieldTagName == "select"){
              //do something special
              formField.val(value);
            } else if(fieldTagName == "textarea"){
              //do something special
              formField.val(value);
            } else {
              formField.val(value);
            }

          }
        })
        if(setting.isDebug){
          alert(debugInfo);
        }
      }
      return form;    //返回对象，提供链式操作
    }
  });
})(jQuery)